package cn.cs.filter;


import cn.cs.common.DtoUtil;
import cn.cs.common.EmptyUtils;
import cn.cs.common.TokenUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Component
@RefreshScope
public class SecondFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecondFilter.class);
    @Resource
    private TokenUtils tokenUtils;
    /**
     *设置过滤器类型
     * */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    /**
     * 在同一级别内部，可以排优先级，数字越小，优先级越高
     * 甚至可以是负数
     * */
    @Override
    public int filterOrder() {
        return 1;
    }
    /**
     * 根据前一个过滤器的执行结果来判断下一个过滤器是否执行
     * */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.sendZuulResponse();
    }


    @Override
    public Object run() {
        System.out.println("access 2");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestUrl = request.getRequestURI().toString();
        String token = request.getHeader("token");

        if (requestUrl.contains("/wxApi/")) {
            LOGGER.info("这里是微信的接口过滤");
            if (tokenUtils.validate("unknown", token)) {
                return DtoUtil.returnFail("token不存在或者失效", "token001");
            }
            return "pass";
        }else if(requestUrl.contains("/appApi/")){
            LOGGER.info("这里是App的接口过滤");
            Map<String,Object> tokenMap = tokenUtils.checkToken(request.getHeader("agent"),token,request.getHeader("code"));
            if("0".equals(tokenMap.get("errorCode"))){
                return  DtoUtil.returnFail(tokenMap.get("errorMsg").toString(),"003");
            }else{
                if("1".equals(tokenMap.get("errorCode"))){
                    return  DtoUtil.returnFail("token已过期请置换token","004");
                }
            }
        }else if(requestUrl.contains("/csPlatform/")){
            LOGGER.info("这里是平台的接口过滤");
            return "pass";
        }
        return "pass";
    }
}
